package com.zzh.demo.provider1.framework.filter;

import com.zzh.demo.core.common.constants.Constants;
import com.zzh.demo.core.common.utils.BasicAuthorizeUtils;
import com.zzh.demo.core.wrapper.RequestWrapper;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * description： <br>
 * createTime: 2018/1/415:17 <br>
 *
 * @author zzh
 */
//@Component
//@WebFilter(urlPatterns = "*", filterName = "ProxyFilter")
public class BasicAuthorizeFilter implements Filter{

//    @Value("${feign.provider1.user}")
    private String user = "zzh";

//    @Value("${feign.provider1.password}")
    private String password = "123456";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = new RequestWrapper((HttpServletRequest) servletRequest);
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String basicString = request.getHeader(Constants.HEADER_NAME_BASIC_AUTHORIZE);
        if(!BasicAuthorizeUtils.basicAuthorize(basicString, user, password)) {
            response.setStatus(401); //设置好相应的状态
            response.setHeader("WWW-Authenticate", "Basic realm=\"My Application\"");

            //设置用户取消验证后的消息提示
            response.setContentType("text/html; charset=UTF-8");
            try(PrintWriter out = response.getWriter()) {
                out.write("未授权");
            }
            return;
        }
        filterChain.doFilter(request, response);
    }


    @Override
    public void destroy() {

    }
}